<template>
  <el-select v-model="vData" v-bind="attribute" :remote-method="getMerchants">
    <el-option
      v-for="item in list"
      :key="item.subMchId"
      :label="item.name"
      :value="item.subMchId"
    ></el-option>
  </el-select>
</template>
<script>
// 店铺选择组件
export default {
  name: 'SubMchSelect',
  props: {
    value: {
      type: [Object, String],
      default: null
    },
    noPermission: {
      type: Boolean,
      default: false
    },
    // 店铺状态， 默认全部查询，0 停用的店铺 1 启用的店铺
    status: {
      type: Number,
      default: undefined
    }
  },
  data () {
    return {
      vData: '',
      list: [],
      baseList: []
    }
  },
  watch: {
    value: {
      handler (data) {
        if (data && this.list.length == 0) {
          this.vData = this.value
          this.getBaseList()
        }
        // 新增时打开，删除已有值
        if (!data) {
          this.getMerchants()
          this.vData = ''
        }
      },
      immediate: true
    },
    vData: {
      handler (data) {
        this.$emit('input', data)
      }
    },
    list (n) {
      if (n?.length > 50) {
        this.list.length = 50
      }
    }
  },
  computed: {
    attribute () {
      return {
        valueKey: 'subMchId',
        clearable: true,
        filterable: true,
        remote: true,
        placeholder: '请输入店铺名称搜索',
        ...this.$attrs
      }
    }
  },
  created () {
    this.getMerchants()
  },
  methods: {
    getMerchants (name = '') {
      this.$POST(
        `sot-admin-api/merchant/sub/${
          this.noPermission ? 'queryListForNoPermission' : 'queryListForMch'
        }`,
        {
          name: name,
          status: this.status
        }
      ).then(res => {
        this.list = res.data.map(item => {
          return {
            subMchId: item.subMchId,
            name: item.name
          }
        })
        // 限制最多显示50条
        if (this.list.length > 50) {
          this.list.length = 50
        }
        if (
          this.baseList.length > 0 &&
          this.list.filter(item => item.subMchId == this.baseList[0].subMchId)
            .length == 0
        ) {
          this.list.push(...this.baseList)
        }
      })
    },
    getBaseList () {
      this.$POST(
        `sot-admin-api/merchant/sub/${
          this.noPermission ? 'queryListForNoPermission' : 'queryListForMch'
        }`,
        {
          subMchId: this.vData,
          status: this.status
        }
      ).then(res => {
        this.list = this.baseList = res.data.map(item => {
          return {
            subMchId: item.subMchId,
            name: item.name
          }
        })
      })
    }
  }
}
</script>
